#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import shutil
import platform

PROJECT_NAME = "zhxy-activity"

def build_executable():
    """
    构建可执行文件的脚本
    添加必要的隐藏导入以确保打包后的程序能正常运行
    """

    # PyInstaller需要添加的隐藏导入模块
    hidden_imports = [
        'PIL',
        'PIL._tkinter_finder',
        'PIL.Image',
        'PIL.ImageTk'
    ]

    # 构建隐藏导入参数
    hidden_import_args = []
    for imp in hidden_imports:
        hidden_import_args.extend(['--hidden-import', imp])

    # 根据操作系统设置可执行文件名称
    system = platform.system().lower()
    if system == "linux":
        executable_name = f"{PROJECT_NAME}_linux"
    elif system == "windows":
        executable_name = f"{PROJECT_NAME}_win"
    elif system == "darwin":  # macOS
        executable_name = f"{PROJECT_NAME}_mac"
    else:
        executable_name = f"{PROJECT_NAME}"

    # PyInstaller命令
    cmd = [
        'pyinstaller',
        '--noconfirm',              # 不询问确认
        '--onefile',                # 打包成单文件 (可以改为 --onedir 以生成文件夹)
        '--windowed',               # 窗口模式 (无控制台窗口)
        '--name', executable_name   # 可执行文件名称
    ]

    # 添加隐藏导入参数
    cmd.extend(hidden_import_args)

    # 添加源文件路径
    cmd.append('src/main.py')

    print("执行构建命令:")
    print(' '.join(cmd))
    print("-" * 50)

    try:
        # 执行PyInstaller命令
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print("构建成功!")
        print(result.stdout)

        # 如果有stderr输出也打印出来
        if result.stderr:
            print("STDERR:", result.stderr)

    except subprocess.CalledProcessError as e:
        print("构建失败!")
        print("返回码:", e.returncode)
        print("STDOUT:", e.stdout)
        print("STDERR:", e.stderr)
        sys.exit(1)

    except FileNotFoundError:
        print("错误: 找不到 pyinstaller 命令")
        print("请确保已安装 pyinstaller:")
        print("pip install pyinstaller")
        sys.exit(1)


def clean_build():
    """清理之前的构建文件"""
    dirs_to_remove = ['build', 'dist']
    files_to_remove = [f for f in os.listdir('.') if f.endswith('.spec')]

    for d in dirs_to_remove:
        if os.path.exists(d):
            shutil.rmtree(d)
            print(f"已删除目录: {d}")

    for f in files_to_remove:
        os.remove(f)
        print(f"已删除文件: {f}")


def main():
    """主函数"""
    print("0.3 抢活动 构建脚本")
    print("=" * 50)

    if len(sys.argv) > 1 and sys.argv[1] == 'clean':
        print("清理构建文件...")
        clean_build()
        return

    print("开始构建可执行文件...")
    build_executable()

    print("\n构建完成!")
    print("可执行文件位于 dist/ 目录下")


if __name__ == '__main__':
    main()
